package com.igoal.web.validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import com.igoal.dto.NewsDTO;

public class AddNewsValidator implements Validator {
	private static final Log logger = LogFactory.getLog(AddNewsValidator.class);
	
	public AddNewsValidator() {
		logger.info("Initializing AddNewsValidator ...");
	}
	
	@SuppressWarnings("rawtypes")
	public boolean supports(Class clazz) {
		return NewsDTO.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		NewsDTO dto = (NewsDTO) target;
		if(StringUtils.isBlank(dto.getBody())){
			errors.rejectValue("body", "error.field.required");
			logger.info("News's body is empty");
		}
		
		if(StringUtils.isBlank(dto.getTitle())){
			errors.rejectValue("title", "error.field.required");
			logger.info("News's title is empty");
		}else if(dto.getTitle().length() > 255){
			errors.rejectValue("title", "error.field.maxlength", new Object[] {new Integer(255)}, null);
		}
		
		if(StringUtils.isBlank(dto.getIntro())){
			errors.rejectValue("intro", "error.field.required");
			logger.info("News's intro is empty");
		}else if(dto.getIntro().length() > 500){
			errors.rejectValue("intro", "error.field.maxlength", new Object[] {new Integer(500)}, null);
		}
		
		if(!StringUtils.isBlank(dto.getKeywords()) && dto.getKeywords().length() > 500){
			errors.rejectValue("keywords", "error.field.maxlength", new Object[] {new Integer(500)}, null);
		}
		
		if(!StringUtils.isBlank(dto.getDescription()) && dto.getDescription().length() > 500){
			errors.rejectValue("descriptions", "error.field.maxlength", new Object[] {new Integer(500)}, null);
		}
		
		if(StringUtils.isBlank(dto.getAvatar()) && (dto.getAvatarFile() == null || dto.getAvatarFile().getSize() == 0)){
			errors.rejectValue("avatarFile", "error.field.required");
		}
	}

}
